<?php

if( !defined( 'MEDIAWIKI' ) )
die(-1);

require_once('DatabaseFunctions.php');

#install extension hook
$wgExtensionFunctions[] = "wfMostFavorited";


function wfMostFavorited(){
  global $wgRequest, $wgDBprefix, $wgOut, $wgUser, $IP, $wgUserLevels;
  $value = $wgRequest->getText( 'title' );
  $values = explode(":", $value);

  //First check if the type of content (url) is the kind to render this module (Main_Page)
  //if ($values[0] == 'Main_Page') {
  if ($value == 'Category:All') {
    $wgOut->setOrder(-90);
    $wgOut->switchBocataMode(false);
    $dbr = wfGetDB( DB_SLAVE );

    //fetch the list of artist most favorited
    $sql1 = "SELECT *, COUNT(*) as fav_counts FROM ss_ilikethis GROUP BY artistkey ORDER BY fav_counts DESC;";
    $res1 = $dbr->query( $sql1 );

    //fetch the list of songs most favorited
    $sql2 = "SELECT *, COUNT(*) as fav_counts FROM ss_ilikethis WHERE type = 2 GROUP BY noArtistkey ORDER BY fav_counts DESC;";
    $res2 = $dbr->query( $sql2 );

    //fetch the list of albums most favorited
    $sql3 = "SELECT *, COUNT(*) as fav_counts FROM ss_ilikethis WHERE type = 3 GROUP BY noArtistkey ORDER BY fav_counts DESC;";
    $res3 = $dbr->query( $sql3 );


    
    $out .= '<div class="home_module" id="mostfavorited">';
    $out .= '<h2>'.wfMsg( 'most_favorited' ).'</h2>';

    //artists
    $count = 0;
    $out .= '<ul><li>'.wfMsg('Artists').'</li>';
    while ($count < 10) { //paint just first 5 most favotted artists
        
          $row = $dbr->fetchObject( $res1 );        
          $out .= '<li>';
          $out .= '<a title="'.$row->artist.'" href="/music/'.urlencode($row->artist).'">'.$row->artist.'</a>';
	  $out .= '</li>';
          $count ++;
          
    }
    $out .= '</ul>';
    $dbr->freeResult( $res1 );

    //songs
    $count = 0;
    $out .= '<ul><li>'.wfMsg('Songs').'</li>';
    while ($count < 10) { //paint just first 5 most favotted artists

          $row2 = $dbr->fetchObject( $res2 );
          $out .= '<li>';
          $out .= '<a title="'.$row2->noArtist.'" href="/download/'.urlencode($row2->artist).'/'.urlencode($row2->noArtist).'">'.$row2->noArtist.'</a>';
	  $out .= '</li>';
          $count ++;

    }
    $out .= '</ul>';
    $dbr->freeResult( $res2 );

    //albums
    $count = 0;
    $out .= '<ul><li>'.wfMsg('Albums').'</li>';
    while ($count < 10) { //paint just first 10 most favotted albums

          $row3 = $dbr->fetchObject( $res3 );
          $out .= '<li>';
          $out .= '<a title="'.$row3->noArtist.'" href="/music/'.urlencode($row3->artist).'/album/'.urlencode($row3->noArtist).'">'.$row3->noArtist.'</a>';
	  $out .= '</li>';
          $count ++;

    }
    $out .= '</ul>';
    $dbr->freeResult( $res3 );

    $out .= '</div>';
    
    
    
    $wgOut->addHtml($out);
    //$wgOut->resetOrder();
  }
}
